<template>
  <div class="publish-textbook">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>发布教材</span>
        </div>
      </template>
      
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        style="max-width: 800px"
      >
        <el-form-item label="教材名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入教材名称" />
        </el-form-item>
        
        <el-form-item label="作者" prop="author">
          <el-input v-model="form.author" placeholder="请输入作者" />
        </el-form-item>
        
        <el-form-item label="出版社" prop="publisher">
          <el-input v-model="form.publisher" placeholder="请输入出版社" />
        </el-form-item>
        
        <el-form-item label="ISBN" prop="isbn">
          <el-input v-model="form.isbn" placeholder="请输入ISBN号" />
        </el-form-item>
        

        
        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="form.price"
            :min="0"
            :precision="2"
            placeholder="请输入价格"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="原价" prop="original_price">
          <el-input-number
            v-model="form.original_price"
            :min="0"
            :precision="2"
            placeholder="请输入原价（可选）"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="成色" prop="condition">
          <el-select v-model="form.condition" placeholder="请选择成色" style="width: 100%">
            <el-option label="全新" value="new" />
            <el-option label="九成新" value="like_new" />
            <el-option label="八成新" value="good" />
            <el-option label="七成新" value="fair" />
            <el-option label="六成新" value="poor" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="教材描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="5"
            placeholder="请输入教材描述，如：教材状态、使用情况、笔记情况等"
          />
        </el-form-item>
        
        <el-form-item label="图片">
          <el-upload
            class="upload-demo"
            action="#"
            :auto-upload="false"
            :on-change="handleImageChange"
            :file-list="fileList"
            list-type="picture-card"
            :limit="5"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">最多上传5张图片，建议图片大小不超过2MB</div>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">发布教材</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="$router.back()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { textbookApi } from '../api/textbook'

const router = useRouter()
const formRef = ref(null)
const loading = ref(false)
const fileList = ref([])

const form = reactive({
  title: '',
  author: '',
  publisher: '',
  isbn: '',
  seller_id: null, // 稍后从localStorage获取
  price: 0,
  original_price: null,
  condition: 'good',
  description: '',
  images: []
})

const rules = {
  title: [
    { required: true, message: '请输入教材名称', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格必须大于0', trigger: 'blur' }
  ],
  condition: [
    { required: true, message: '请选择成色', trigger: 'change' }
  ]
}



// 处理图片上传
  const handleImageChange = (file, fileList) => {
    console.log('Image changed:', file, fileList);
    // 清空之前的图片数据
    form.images = [];
    
    // 为每个文件创建预览并转换为base64，同时限制大小
    fileList.forEach(item => {
      if (item.raw) {
        // 检查文件大小，超过2MB的文件不上传
        if (item.size > 2 * 1024 * 1024) {
          ElMessage.warning(`文件 ${item.name} 超过2MB，请选择更小的图片`);
          return;
        }
        
        const reader = new FileReader();
        reader.onload = (e) => {
          let base64Data = e.target.result;
          
          // 确保base64数据格式正确，检查是否包含data:image前缀
          if (!base64Data || typeof base64Data !== 'string' || !base64Data.startsWith('data:image/')) {
            console.error('Invalid base64 format, missing data:image prefix');
            ElMessage.error('图片格式错误，请重新选择图片');
            return;
          }
          
          // 限制base64字符串长度，防止数据过长
          if (base64Data.length > 50000) {
            // 如果数据过长，我们可以尝试使用canvas压缩
            compressImage(base64Data, (compressedData) => {
              // 验证压缩后的数据格式
              if (compressedData && typeof compressedData === 'string' && compressedData.startsWith('data:image/')) {
                form.images.push(compressedData);
                console.log('Compressed image data added:', compressedData.substring(0, 100) + '...');
              } else {
                console.error('Compressed data format is invalid');
                ElMessage.error('图片压缩失败，请尝试其他图片');
              }
            });
          } else {
            form.images.push(base64Data);
            console.log('Base64 image data added:', base64Data.substring(0, 100) + '...');
          }
        };
        reader.onerror = (error) => {
          console.error('文件读取失败:', error);
          ElMessage.error('图片读取失败，请重新选择图片');
        };
        reader.readAsDataURL(item.raw);
      }
    });
  };
  
  // 图片压缩函数
  const compressImage = (base64Data, callback) => {
    try {
      // 参数验证
      if (!base64Data || typeof base64Data !== 'string') {
        console.error('Invalid base64 data provided');
        callback(null);
        return;
      }
      
      const img = new Image();
      img.crossOrigin = 'Anonymous'; // 防止跨域问题
      img.src = base64Data;
      
      img.onload = () => {
        try {
          // 创建canvas
          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');
          
          if (!ctx) {
            console.error('Canvas context not available');
            callback(null);
            return;
          }
          
          // 设置压缩后的尺寸（保持宽高比）
          const maxWidth = 800;
          const maxHeight = 600;
          let width = img.width;
          let height = img.height;
          
          // 计算压缩比例
          const ratio = Math.min(maxWidth / width, maxHeight / height);
          width *= ratio;
          height *= ratio;
          
          canvas.width = width;
          canvas.height = height;
          
          // 绘制图片前清空画布
          ctx.clearRect(0, 0, width, height);
          
          // 绘制图片
          ctx.drawImage(img, 0, 0, width, height);
          
          try {
            // 转换为压缩后的base64，确保使用正确的MIME类型
            const mimeType = 'image/jpeg';
            const compressedData = canvas.toDataURL(mimeType, 0.7);
            
            if (compressedData && typeof compressedData === 'string' && compressedData.startsWith('data:image/')) {
              // 确保数据长度在合理范围内
              if (compressedData.length > 100000) {
                // 进一步降低质量
                const furtherCompressed = canvas.toDataURL(mimeType, 0.5);
                callback(furtherCompressed);
              } else {
                callback(compressedData);
              }
            } else {
              console.error('Failed to generate valid base64 data');
              callback(null);
            }
          } catch (toDataURLError) {
            console.error('Error generating data URL:', toDataURLError);
            callback(null);
          }
        } catch (error) {
          console.error('Error during image compression:', error);
          callback(null);
        }
      };
      
      img.onerror = () => {
        console.error('图片加载失败');
        callback(null);
      };
      
      // 设置图片加载超时
      setTimeout(() => {
        if (img.complete === false) {
          console.error('图片加载超时');
          callback(null);
        }
      }, 5000);
    } catch (error) {
      console.error('Compression function error:', error);
      callback(null);
    }
  }

// 提交表单
const submitForm = async () => {
  try {
    if (!formRef.value) return
    
    // 获取当前登录用户信息
    const userStr = localStorage.getItem('user')
    if (!userStr) {
      ElMessage.error('请先登录')
      return
    }
    
    // 解析用户数据并添加完善的错误处理
    let userData;
    try {
      userData = JSON.parse(userStr)
    } catch (parseError) {
      console.error('用户数据解析错误:', parseError)
      ElMessage.error('用户数据异常，请重新登录')
      return
    }
    
    // 确保正确获取用户ID
    const userId = userData.user_id || userData.id
    if (!userId) {
      ElMessage.error('无法获取用户信息，请重新登录')
      return
    }
    
    form.seller_id = userId
    console.log('提交的seller_id:', form.seller_id)
    
    await formRef.value.validate(async (valid) => {
      if (valid) {
        loading.value = true
        try {
          // 处理作者字段（支持多个作者），并处理空字符串情况
          const authors = form.author ? 
            form.author.split(',').map(a => a.trim()).filter(Boolean) : []
            
          const submitData = {
            ...form,
            author: authors.length > 0 ? authors.join(', ') : null,
            status: 'on_sale' // 确保设置默认状态
          }
          
          console.log('提交的教材数据:', submitData)
          
          const response = await textbookApi.createTextbook(submitData)
          console.log('发布成功响应:', response)
          
          if (response.success) {
            ElMessage.success('发布成功')
            router.push('/textbooks')
          } else {
            ElMessage.error(response.message || '发布失败')
          }
        } catch (error) {
          console.error('发布失败:', error)
          ElMessage.error('发布失败: ' + (error.message || '未知错误'))
        } finally {
          loading.value = false
        }
      } else {
        ElMessage.error('表单验证失败，请检查必填项')
      }
    })
  } catch (error) {
    console.error('提交过程出错:', error)
    ElMessage.error('系统错误，请稍后重试')
  }
}

// 重置表单
const resetForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
  form.images = []
  fileList.value = []
}

onMounted(() => {
  // 页面加载完成
})
</script>

<style scoped>
.publish-textbook {
  max-width: 1000px;
  margin: 0 auto;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}

.upload-tip {
  margin-top: 10px;
  font-size: 12px;
  color: #909399;
}
</style>

